package com.code.chatroom.server

import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.ChannelFuture
import io.netty.channel.ChannelOption
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.NioServerSocketChannel
import java.net.InetAddress

/**
 * 聊天室服务器
 */
class ChatRoomServer(private val port : Int = 7651) {

    /**
     * 启动服务器
     */
    fun start(){
        print("\u001B[32m启动服务器...\u001B[0m")
        // 创建两个线程组
        val bossGroup = NioEventLoopGroup(1)
        // 默认启动线程个数为：CPU核数 * 2
        val workerGroup = NioEventLoopGroup()
        // 创建服务器程序的启动器
        val serverBootstrap = ServerBootstrap()
        // 配置服务器参数
        serverBootstrap.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel::class.java)                // 采用NioServerSocketChannel做为服务器的通道实现类
            .option(ChannelOption.SO_BACKLOG, 128)          //  设置线程队列等待连接的个数
            .childOption(ChannelOption.SO_KEEPALIVE, true)  // 保持连接的活动状态
            .childHandler(InitChannelHandler())

        try {
            // 绑定到端口，即正式启动服务器
            val future : ChannelFuture = serverBootstrap.bind(port).sync()
            println("\u001B[32m成功！[host: ${InetAddress.getLocalHost().hostAddress}, port: $port]\u001B[0m")
            // 监听关闭
            future.channel().closeFuture().sync()
        }catch (e : Exception){
            println("\u001B[6D\u001B[K\u001B[31m失败！${port}端口已被占用\u001B[0m")
        }finally {
            bossGroup.shutdownGracefully()
            workerGroup.shutdownGracefully()
        }

    }
}